<?php

/**
 *
 * 版权所有：恰维网络<qwadmin.qiawei.com>
 * 作    者：寒川<hanchuan@qiawei.com>
 * 日    期：2015-09-17
 * 版    本：1.0.0
 * 功能说明：模块公共文件。
 *
 * */
function UpImage($callBack = "image", $width = 100, $height = 100, $image = "") {
    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" width=' . $width . ' height="' . $height . '"  src="' . U('Upload/uploadpic', array("Width" => $width, "Height" => $height, "BackCall" => $callBack, "Img" => $image)) . '"></iframe>
         <input type="hidden" name="' . $callBack . '" id="' . $callBack . '">';
}

function BatchImage($callBack = "image", $width = 100, $height = 100, $image = "") {
    echo '<iframe scrolling="no" frameborder="0" border="0" width=100% onload="this.height=this.contentWindow.document.body.scrollHeight;" src="' . U('Upload/batchpic') . '?BackCall=' . $callBack . '&Img=' . $image . '"></iframe>
		<input type="hidden" name="' . $callBack . '" id="' . $callBack . '">';
}

function UpImage1($callBack = "image", $width = 100, $height = 100, $image = "") {
    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" width=' . $width . ' height="' . $height . '"  src="' . U('Upload/uploadpic', array("Width" => $width, "Height" => $height, "BackCall" => $callBack, "Img" => $image)) . '"></iframe>
         <input type="hidden" name="' . $callBack . '" id="' . $callBack . '">';
}

function BatchImage1($callBack = "image", $width = 100, $height = 100, $image = "") {
    echo '<iframe scrolling="no" frameborder="0" border="0" width=100% onload="this.height=this.contentWindow.document.body.scrollHeight;" src="' . 'http://localhost/qwadmin/index.php/qwadmin/Upload/batchpic' . '?BackCall=' . $callBack . '&Img=' . $image . '"></iframe>
		<input type="hidden" name="' . $callBack . '" id="' . $callBack . '">';
}

/*
 * 函数：网站配置获取函数
 * @param  string $k      可选，配置名称
 * @return array          用户数据
 */

function setting($k = 'all') {
    $cache = S($k);
    //如果缓存不为空直接返回
    if (null != $cache) {
        return $cache;
    }
    $data = '';
    $setting = M('setting');
    //判断是否查询全部设置项
    if ($k == 'all') {
        $setting = $setting->field('k,v')->select();
        foreach ($setting as $v) {
            $config[$v['k']] = $v['v'];
        }
        $data = $config;
    } else {
        $result = $setting->where("k='{$k}'")->find();
        $data = $result['v'];
    }
    //建立缓存
    if ($data) {
        S($k, $data);
    }
    return $data;
}

/**
 * 函数：格式化字节大小
 * @param  number $size 字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) {
        $size /= 1024;
    }
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 函数：加密
 * @param string            密码
 * @return string           加密后的密码
 */
function password($password) {
    /*
     * 后续整强有力的加密函数
     */
    return md5('Q' . $password . 'W');
}

/**
 * 随机字符
 * @param number $length 长度
 * @param string $type 类型
 * @param number $convert 转换大小写
 * @return string
 */
function random($length = 6, $type = 'string', $convert = 0) {
    $config = array(
        'number' => '1234567890',
        'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if (!isset($config[$type])) {
        $type = 'string';
    }
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
        $code .= $string{mt_rand(0, $strlen)};
    }
    if (!empty($convert)) {
        $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
    }
    return $code;
}

//获取所有的子级id
function category_get_sons($sid, &$array = array()) {
    //获取当前sid下的所有子栏目的id
    $categorys = M("category")->where("pid = {$sid}")->select();

    $array = array_merge($array, array($sid));
    foreach ($categorys as $category) {
        category_get_sons($category['id'], $array);
    }
    $data = $array;
    unset($array);
    return $data;
}

/*
  $trade_data = array(
  'ref' => '2016101714513810',
  'channel_code' => 'ec',
  'trade_pattern' => 'b1',
  'date_order' => '2016-10-17 14:16:16',
  'buyer' => '2973738594@qq.com',
  'seller' => '532427264@qq.com',
  'receive_info' => '黄翠连|17783067698|中国|重庆|重庆市|南岸区|重庆市南岸区学府大道33号交科院10栋|530200',
  'total_import_taxes' => '8.810',
  'amount_untaxed' => '69.000',
  'amount_total' => '82.810',
  'delivery_fee' => '5.000',
  'buyer_reg_no' => '2973738594@qq.com',
  'buyer_name' => '黄翠连',
  'buyer_id_type' => '1',
  'buyer_id_card' => '450121199101144524',
  'order_line' =>
  array(
  0 =>
  array(
  'sku' => 'P0042007',
  'name' => '(保税)德国 Lavera 柠檬平衡洗发露200ml',
  'price' => 69,
  'num' => 1,
  'tax_fee' => '8.806',
  'sub_total' => '77.806',
  'sub_total_untaxed' => 69,
  ),
  ),
  'payment_line' =>
  array(
  0 =>
  array(
  'payment_account' => 'alipay',
  'payamount' => 82.81,
  'payment_no' => '14766849855438',
  ),
  ),
  'ebpCode' => '50089609A8',
  );

 * 添加商品订单  若存在 就更新  
 * 顺带添加 payLine  orderItem添加
 */

/**
 * 
 * @param type $order
 * @param type $msg
 * @return boolean
 */
function addOrder($order, &$msg = "") {
    $ref = $order['ref'];
    $orderModel = M("Order");
    $order_lineModel = M("Order_line");
    $order_paymentModel = M("Order_payment");
    $res = $orderModel->where(array("ref" => $ref))->find();



    $data = array(
//        "ref"=>$order['ref'],
        "channel_code" => $order['channel_code'],
        "trade_pattern" => $order['trade_pattern'],
        "date_order" => $order['date_order'],
        "buyer" => $order['buyer'],
        "seller" => $order['seller'],
        "receive_info" => $order['receive_info'],
        "total_import_taxes" => $order['total_import_taxes'],
        "amount_untaxed" => $order['amount_untaxed'],
        "amount_total" => $order['amount_total'],
        "delivery_fee" => $order['delivery_fee'],
        "buyer_reg_no" => $order['buyer_reg_no'],
        "buyer_name" => $order['buyer_name'],
        "buyer_id_type" => $order['buyer_id_type'],
        "buyer_id_card" => $order['buyer_id_card'],
        "ebpCode" => $order['ebpCode'],
        "create_time" => date("Y-m-d H:i:s"),
        "state" => $order['state'] ? $order['state'] : 0,
    );



    //开启事务

    $orderModel->startTrans();
    if ($res) {
        //更新
        $insertorder = $res['id'];
        $flage1 = $orderModel->where(array("ref" => $ref))->save($data);
    } else {
        $data['ref'] = $ref;
        $insertorder = $flage1 = $orderModel->add($data);
    }

    if ($flage1 === false) {
        $msg = "插入失败";
        $orderModel->rollback();
        return FALSE;
    }

    //先删除原有字段   在添加
    $order_lineModel->where(array("ref" => $ref))->delete();
    $orderlinedata = $order['order_line'];
    $orderline = array();

    foreach ($orderlinedata as $key => $value) {

        $orderline[$key] = array(
            "order_id" => $insertorder,
            "ref" => $ref,
            "sku" => $value['sku'],
            "name" => $value['name'],
            "price" => $value['price'],
            "num" => $value['num'],
            "tax_fee" => $value['tax_fee'],
            "sub_total" => $value['sub_total'],
            "sub_total_untaxed" => $value['sub_total_untaxed'],
            "create_time" => date("Y-m-d H:i:s"),
            "date_order" => $order['date_order'],
        );
    }

    $flag = $order_lineModel->addAll($orderline);


    if ($flag === false) {
        $msg = "插入orderline失败";
        $orderModel->rollback();
        return FALSE;
    }

    //先删除原有字段   在添加

    $order_paymentdata = $order['payment_line'];
    if ($order_paymentdata) {

        $order_paymentModel->where(array("ref" => $ref))->delete();
        $order_pay = array();
        foreach ($order_paymentdata as $key => $value) {

            $order_pay[$key] = array(
                "order_id" => $insertorder,
                "ref" => $ref,
                "payment_account" => $value['payment_account'],
                "payamount" => $value['payamount'],
                "payment_no" => $value['payment_no'],
                "create_time" => date("Y-m-d H:i:s"),
            );
        }
        $flag = $order_paymentModel->addAll($order_pay);

        if ($flag === false) {
            $msg = "插入orderpay失败";
            $orderModel->rollback();
            return FALSE;
        }
    }

    //更新或插入 订单详情 和 支付清单

    $orderModel->commit();
    return true;
}

/**
  采购单添加
 * */
function addpurchorder($order, &$msg) {
    $modelorder = M('purchorder');
    $modelline = M('purchorder_line');

    ///var_dump(array('POname'=>$order['POname']));
    $ord = $modelorder->where(array('poname' => $order['poname']))->find();
    ///echo "--->";
    ///var_dump($ord);
    ///echo "--->";
    $modelorder->startTrans();
    $lines = $order['line'];
    unset($order['line']);

    if ($ord) {
        $re = $modelorder->save($order);
        if ($re === false) {
            $modelorder->rollback();
            $msg = "order保存失败";
            return false;
        }
    } else {
        $re = $modelorder->add($order);
        if ($re === false) {
            $modelorder->rollback();
            $msg = "order添加失败";
            return false;
        }
    }
    ////更新订购清单
    if ($lines) {
        foreach ($lines as $i => $l) {

            $ld = $modelline->where(array('hash' => $l['hash']))->find();
            if ($ld) {
                $re = $modelline->save($l);
                if ($re === false) {
                    $modelorder->rollback();
                    $msg = "lline保存失败";
                    return false;
                }
            } else {
                $re = $modelline->add($l);
                if ($re === false) {
                    $modelorder->rollback();
                    $msg = "lline保存失败";
                    return false;
                }
            }
        }
    }

    $modelorder->commit();
    return true;
}

/*
  进件申报单提交
 */

function addtransorder($order, &$msg) {
    $modelorder = M('transorder');
    $modelline = M('transorder_lines');

    $ord = $modelorder->where(array('toname' => $order['toname']))->find();

    $modelorder->startTrans();
    $lines = $order['lines'];
    unset($order['lines']);
    if ($ord) {
        $re = $modelorder->save($order);
    } else {
        $re = $modelorder->add($order);
    }
    ////更新订购清单
    if ($lines) {
        foreach ($lines as $i => $l) {

            $ld = $modelline->where(array('flag' => $l['flag'], 'from_flag' => $l['from_flag']))->find();
            if ($ld) {
                $re = $re . $modelline->save($l);
            } else {
                $re = $re . $modelline->add($l);
            }
        }
    }

    $modelorder->commit();
}

function addstockpicking($order, &$msg) {
    $modelorder = M('stock_picking');
    $modelline = M('stock_moveline');
    $ord = $modelorder->where(array('pick_id' => $order['pick_id']))->find();
    $modelorder->startTrans();
    $lines = $order['lines'];
    unset($order['lines']);
    //var_dump($ord);
    if ($ord) {
        $re = $modelorder->save($order);
    } else {
        $re = $modelorder->add($order);
    }


    ////更新moveline
    if ($lines) {
        foreach ($lines as $i => $l) {

            $ld = $modelline->where(array('sku' => $l['sku'], 'qty' => $l['qty'], 'picking_id' => $l['picking_id'], 'date' => $l['date']))->find();
            if ($ld) {
                echo "modify line." . $l['picking_id'] . "<br/>";
                $re = $re . $modelline->save($l);
            } else {
                echo "add line." . $l['picking_id'] . "<br/>";
                $re = $re . $modelline->add($l);
            }
        }
    }
    /*
      5 盘存盈亏
      6 补货
      7 生产 8 供应商 9 客户
      11 WH 12 库存 18 WH 21 播种库位 24 墙库位
     */
    ///var_dump($re);
    ///内部移动
    $modelline->execute("UPDATE zt_stock_moveline SET qty_act=0 WHERE   location_id NOT IN (8,9,5) AND location_dest_id NOT IN (8,9,5)");
    ///供应商
    $modelline->execute("UPDATE zt_stock_moveline SET qty_act=qty WHERE   location_id  IN (5,8,9)");
    ///客户
    $modelline->execute("UPDATE zt_stock_moveline SET qty_act=-qty WHERE   location_dest_id  IN (5,8,9)");

    $modelorder->commit();
}

/**
 * 对外的站点用户添加
 * @param type $data
 * @param type $site_id
 * 
 */
function site_memberadd($data, $site_id, &$msg = "") {

    $memberdata = array(
        'name' => $data['name'],
        'phone' => $data['phone'] ? $data['phone'] : "",
        'mobile' => $data['mobile'],
        'email' => $data['email'],
        'street' => $data['street'],
        'city' => $data['city'],
        'province' => $data['province'],
        'country' => $data['country'],
        'contact_address' => $data['contact_address'],
        'is_seller' => (strtolower($data['is_seller']) == "true") ? "True" : "False",
        'create_time' => time(),
    );
    $where = array('id' => $data['id'], 'site_id' => $site_id);
    $membermodel = M("site_member");
    $has = $membermodel->where($where)->find();
    if ($has) {
        //更新
        $flag = $membermodel->where($where)->save($data);
    } else {
        //insert
        $memberdata = array_merge($memberdata, $where);
        $flag = $membermodel->add($memberdata);
    }
    if ($flag === FALSE) {
        $msg = "操作失败";
        return FALSE;
    }
    return true;
}

function get_order_status($status = 0) {
    $ORDER_STATUS = array(
        0 => "未付款",
        1 => "已付款",
        2 => "已发货",
        3 => "已收货",
        4 => "已申请退款",
        5 => "退款异常",
        6 => "退款失败",
        7 => "退款成功"
    );
    return $ORDER_STATUS[$status];
}

/**
 * 消息写入
 * @param string $title 标题
 * @param string $message 内容
 * @param int $target_id 目标ID
 * @param string $role 角色
 */
function system_message($title , $message , $target_id , $role = 1) {
    if( !$title || !$message || !$target_id ) return false;
    $data = array(
        'title' => $title,
        'content' => $message,
        'target_id' => $target_id,
        'role' => $role
    );
    if( D('SystemMessage')->create( $data ) !== false ) {
        return D('SystemMessage')->add();
    }
    return false;
}

/**
 * 格式化时间显示
 * @param type $time
 * @return type
 */
function formatTime( $time ) {
    if( !is_numeric( $time ) ) {
        $time = strtotime( $time );
    }
    $between_time = time() - $time;
    if( $between_time < 60 ) {
        return $between_time . '秒钟前';
    } else if( $between_time < 3600 ) {
        return intval( $between_time / 60 ) . '分钟前';
    } else if( $between_time < 3600 * 24 ) {
        return intval( $between_time / 3600 ) . '小时前';
    } else {
        return date('Y-m-d' , $time);
    }
}

/**
 * 更新商品热度
 * @param int $goods_id 商品ID
 */
function hotSortNumSave( $goods_id ) {
	if( !$goods_id ) return;
	//供应商总数
	$total = M('goods_supply')->where(array('goods_id' => $goods_id , 'stock_status' => 1 , 'status' => 2))->count();
	//供应产品总数
	$stock_num = M('goods_supply')->where(array('goods_id' => $goods_id, 'stock_status' => 1 ,'status' => 2))->sum('stock_num');
	$hot_num = $total * 500 + $stock_num;
	M('goods')->where(array('id' => $goods_id))->save(array('heat_num' => $hot_num));
}

/**
 * 商品供货统计信息
 * @param int $supply_id 供应ID
 * @param string $field 字段名称
 * @param int $num 数量
 * @param int $type 类型
 */
function goods_supply_count_save( $supply_id , $field , $num , $type = 1 ) {
    if( !$supply_id || !$field || !$num ) return false;
    $field = explode( ',' , $field );
    $supply_info = M('goods_supply_count')->where(array('goods_supply_id' => $supply_id))->find();
    if( !$supply_info ) {
        $add_data = array(
            'goods_supply_id' => $supply_id,
            'customer_id' => M('goods_supply')->where(array('id' => $supply_id))->getField('customer_id')
        );
        foreach( $field as $k => $v ) {
            $add_data[$v] = $num;
        }
        M('goods_supply_count')->add( $add_data );
    } else {
        foreach( $field as $k => $v ) {
            $supply_info[$v] = $type == 1 ? $supply_info[$v] + $num : $supply_info[$v] - $num;
            $supply_info[$v] = $supply_info[$v] <= 0 ? 0 : $supply_info[$v];
        }
        M('goods_supply_count')->save( $supply_info );
    }
}